import { dateFormat } from '@/utils';
import { editFiled, addFiled, getFieldDetails } from '@/api/addfiled.js';
import { getCropList, uploadBase64, homepageAddress } from '@/api/addfiled';
import FileUrl from '@/utils/fileUrl';
import { Toast } from 'vant';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import CanvasMap from './canvasMap/index.vue';
import html2canvas from './html2canvas.min.js';
import { dataURLtoFile } from '@/utils/handleImg';

export default {
  name: 'PostNewMap',
  computed: {},
  data() {
    return {
      fieldName: {
        text: 'text',
        value: 'id',
        children: 'children'
      },
      pageInfo: {},
      showDrawField: !this.$route.query.fieldId,
      grounpId: '',
      fieldId: this.$route.query.fieldId,
      address: '',
      Area: '',
      AreaMu: '',
      AreaFen: '',
      perimeter: '',
      altitude: '',
      slope: '',
      allList: [],
      classAll: [],
      class2: [],
      showclickValue: false,
      landTypeList: [
        {
          id: 1,
          name: '确权'
        },
        {
          id: 2,
          name: '流转'
        },
        {
          id: 3,
          name: '托管'
        },
        {
          id: 4,
          name: '其他'
        }
      ],
      isLandType: false,
      landTypeText: '',
      time: '',
      currentDate: new Date(),
      show: false,
      maxDate: '',
      boundary: '',
      img: '',
      center: {},
      isEdtior: false,
      timer: null,
      isshowmodel: false,
      boundaries: null,
      cropList: [],
      map: null,
      baseLayer: null,
      isConfirm: false,
      btnLoading: false
    };
  },
  components: { CanvasMap },
  methods: {
    // 种植作物
    clickValue() {
      this.showclickValue = true;
    },
    /* 选择作物 */
    onConfirmCrop(value) {
      this.pageInfo.cropSubName = value.selectedOptions[1].text;
      this.pageInfo.cropSubId = value.value;
      this.showclickValue = false;
    },
    /* 取消选择作物 */
    onCancelCrop() {
      this.showclickValue = false;
    },
    // 土地类型
    landTypeClick() {
      this.isLandType = true;
    },
    // 选择土地类型
    onLandTypeClick(value) {
      this.landTypeText = value.name;
      this.pageInfo.landType = value.id;
      this.isLandType = false;
    },
    // 播种时间
    clickTime() {
      this.show = true;
    },
    formatter(type, val) {
      if (type === 'year') {
        return val + '年';
      }
      if (type === 'month') {
        return val + '月';
      }
      if (type === 'day') {
        return val + '日';
      }
      return val;
    },
    chooseTime(val) {
      this.show = false;
      this.time = dateFormat('yy-MM-dd', val);
    },
    quxiao() {
      this.show = false;
    },

    /* 面积转换成亩和分 */
    areaToMuFen() {
      if (isNaN(this.Area)) {
        this.AreaMu = 0;
        this.AreaFen = 0;
      } else {
        this.AreaMu = this.Area.split('.')[0];
        this.AreaFen = this.Area.split('.')[1] ? this.Area.split('.')[1] : 0;
      }
    },

    // 修改田 获取田详情
    async getPageInfo() {
      const params = {
        id: this.$route.query.fieldId // 60001 1
      };
      // 获取田详情
      const res = await getFieldDetails(params.id);
      if (res.code == 200) {
        this.pageInfo = res.data;
        this.Area = this.pageInfo.area + '';
        this.areaToMuFen();
        this.perimeter = this.pageInfo.perimeter;
        this.altitude = (this.pageInfo.altitude || 0) + '米';
        this.slope = (this.pageInfo.slope || 0) + '度';
        this.boundary = this.pageInfo.boundary;
        this.center.lng = this.pageInfo.xaxis;
        this.center.lat = this.pageInfo.yaxis;
        this.address = this.pageInfo.address;
        this.pageInfo.cropName = this.pageInfo.cropSubName;
        this.pageInfo.cropSubId = this.pageInfo.cropSubId;
        this.time = this.pageInfo.sowTime;
        this.pageInfo.leader = this.pageInfo.leader;
        if (this.pageInfo.landType) {
          // 根据土地类型id获取土地类型
          this.landTypeList.forEach((item) => {
            if (item.id == this.pageInfo.landType) {
              this.landTypeText = item.name;
              this.pageInfo.landType = item.id;
            }
          });
        }

        /* 计算边界，绘制地图 */
        this.boundaries = [[]];
        const boundaryArr = this.boundary.split(',');
        for (let i = 0; i < boundaryArr.length; i = i + 2) {
          this.boundaries[0].push({
            lng: boundaryArr[i],
            lat: boundaryArr[i + 1]
          });
        }
        this.initMap();
      }
    },

    /* 验证手机号是否正确 */
    validatorPhone(phone) {
      const reg = /^1[3|4|5|6|7|8|9]\d{9}$/; // 手机号正则
      if (phone && !reg.test(phone)) {
        Toast('请填写正确的手机号');
        return false;
      }
      return true;
    },

    // 提交田
    submit() {
      // 边界格式转换
      const axises = [];
      const pointArr = [];
      const latlngs = this.boundaries[0];
      for (const i in latlngs) {
        pointArr.push([+latlngs[i]['lng'], +latlngs[i]['lat']]);
        axises.push(latlngs[i]['lng']);
        axises.push(latlngs[i]['lat']);
      }

      if (!this.pageInfo.fieldName) {
        Toast('请输入田块名称');
        return;
      }
      if (!this.pageInfo.farmerName) {
        Toast('请输入种植农户');
        return;
      }
      if (!this.pageInfo.farmerPhone) {
        Toast('请输入联系方式');
        return;
      }
      if (!this.validatorPhone(this.pageInfo.farmerPhone)) {
        return;
      }
      if (this.pageInfo.landTypeText == '') {
        Toast('请输入土地类型');
        return;
      }

      const area = this.AreaMu + '.' + this.AreaFen;

      this.pageInfo.area = area;
      this.pageInfo.xaxis = this.center.lng.toString();
      this.pageInfo.yaxis = this.center.lat.toString();
      this.pageInfo.address = this.address;
      const altitude = this.altitude.replace('米', '');
      this.pageInfo.altitude = Number(altitude).toFixed(0);
      this.pageInfo.slope = this.slope.replace('度', '');
      this.pageInfo.sowTime = this.time; // 播种时间
      this.pageInfo.boundary = axises.join(); // 边界
      this.pageInfo.perimeter = this.perimeter;
      const param = this.pageInfo;

      this.btnLoading = true;
      if (this.isEdtior) {
        this.canvasImg((img) => {
          param.img = img;
          param.fieldId = this.$route.query.fieldId;
          editFiled(param)
            .then((res) => {
              this.btnLoading = false;
              if (res.code == 200) {
                Toast('操作成功');
                setTimeout(() => {
                  this.$router.go(-1);
                }, 500);
              }
            })
            .catch((err) => {
              this.btnLoading = false;
              Toast(err.msg);
            });
        });
      } else {
        this.canvasImg((img) => {
          param.img = img;
          addFiled(param)
            .then((res) => {
              this.btnLoading = false;
              if (res.code == 200) {
                Toast('操作成功');
                setTimeout(() => {
                  this.$router.go(-1);
                }, 500);
              }
            })
            .catch((err) => {
              this.btnLoading = false;
              Toast(err.msg);
            });
        });
      }
    },

    chageTime(e) {
      console.log(e);
    },

    /* 画田完成 */
    drawMapComp(fieldData, isCancel = false) {
      if (isCancel) {
        this.showDrawField = false;
        return;
      }
      this.isConfirm = true;
      this.showDrawField = false;
      this.Area = fieldData.area;
      this.areaToMuFen();
      this.perimeter = fieldData.perimeter;
      this.center = fieldData.center;
      this.boundaries = fieldData.boundaries;
      this.address = fieldData.address;
      this.altitude = fieldData.altitude + '米';
      this.slope = fieldData.slope + '度';

      this.getHomepageAddress(fieldData.center);
      this.initMap();
    },

    // 经纬度转地区
    async getHomepageAddress(center) {
      const data = {
        lng: center.lng,
        lat: center.lat
      };
      const result = await homepageAddress(data);
      if (result.code == 200) {
        this.address = result.data.regeocode.formatted_address;
      } else {
        this.$toast(result.msg);
      }
    },

    // 截屏绘制
    canvasImg(callback) {
      const _t = this;
      const shareContent = _t.$refs.complateMap;
      const width = shareContent.offsetWidth * 1;
      const height = shareContent.offsetHeight * 1;
      const canvas = document.createElement('canvas');
      const scale = 1;

      canvas.width = width * scale;
      canvas.height = height * scale;
      canvas.getContext('2d').scale(scale, scale);

      const opts = {
        scale: scale,
        canvas: canvas,
        useCORS: true, // 保证图片渲染出来
        logging: true,
        width: width,
        height: height,
        scrollY: 0,
        scrollX: 0
      };
      html2canvas(_t.$refs.complateMap, opts).then((canvas) => {
        var str = canvas.toDataURL('image/png', 1);
        const file2 = dataURLtoFile(str, 'file.png', 'image/png'); // base64 转成文件
        console.log(file2);
        let strindex = str.indexOf(',');
        if (strindex != -1) {
          strindex = strindex + 1;
          var base64Str = str.slice(strindex);
        }
        // let base64Image = `data:image/jpeg;base64,${base64Str}`;
        const fileUrl = FileUrl.setFillUrl('png');
        console.log(fileUrl);
        const data = {
          base64Img: base64Str,
          fileUrl
        }
        uploadBase64(data)
          .then((res) => {
            if (res.code == 200) {
              callback(res.msg);
            } else {
              this.btnLoading = false;
              Toast('绘图失败，请重新操作！');
            }
          })
          .catch(() => {
            this.btnLoading = false;
            Toast('绘图失败，请重新操作！');
          });
      });
    },

    /* 编辑地图边界 */
    editFieldMap() {
      if (this.isEdtior && this.pageInfo.adoptStatus != 2) {
        this.showDrawField = true;
      }
    },

    // 初始化地图
    initMap() {
      if (this.map) {
        this.map.remove();
        this.map = null;
      }
      const map = L.map('complateMap', {
        center: [31.80452471, 118.4253323],
        maxZoom: 19,
        zoom: 14,
        attributionControl: false,
        zoomControl: false,
        dragging: false,
        scrollWheelZoom: false,
        keyboard: false,
        doubleClickZoom: false,
        touchZoom: false,
        boxZoom: false,
        layers: [
          L.tileLayer(
            'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
            {
              maxZoom: 20,
              subdomains: []
            }
          )
        ]
      });
      this.map = map;

      /* 根据边界画多边形 */
      /* 根据边界画多边形 */
      const boundaries = this.boundaries;
      L.polygon(boundaries, {
        fillOpacity: 0.5,
        fillColor: 'green'
      }).addTo(map);

      map.fitBounds(boundaries); // 图形在中心

      /* 地图渲染完成再进行截图 */
      // map.on("moveend", function (e) {
      //     setTimeout(() => {
      //     }, 1000)
      // });
    },

    /* 获取作物列表 */
    async getCropList() {
      const result = await getCropList();
      if (result.code == 200) {
        const resList = result.data;

        const initList = [];
        for (var i = 0; i < resList.length; i++) {
          if (resList[i].cropList && resList[i].cropList.length > 0) {
            const obj = {
              id: resList[i].typeId,
              text: resList[i].typeName,
              children: []
            };
            for (var a = 0; a < resList[i].cropList.length; a++) {
              if (
                resList[i].cropList[a].subList &&
                resList[i].cropList[a].subList.length > 0
              ) {
                const cropObj = {
                  id: resList[i].cropList[a].cropId,
                  text: resList[i].cropList[a].cropName,
                  children: []
                };
                for (
                  var s = 0;
                  s < resList[i].cropList[a].subList.length;
                  s++
                ) {
                  const subObj = {
                    id: resList[i].cropList[a].subList[s].cropSubId,
                    text: resList[i].cropList[a].subList[s].cropSubName
                  };
                  cropObj.children.push(subObj);
                }
                obj.children.push(cropObj);
              }
            }
            initList.push(obj);
          }
        }

        this.cropList = initList;
      }
    }
  },
  mounted() {
    // 获取当前时间设置选择器最大值
    var myDate = new Date();
    this.maxDate = new Date(
      myDate.getFullYear(),
      myDate.getMonth(),
      myDate.getDate()
    );
    this.getCropList();
    const query = this.$route.query;
    if (query.fieldId) {
      this.isEdtior = true;
      this.getPageInfo();
    }
  }
};
